//
//  KouDaiCellPushViewController.m
//  MyProject
//
//  Created by apple on 15/11/3.
//  Copyright (c) 2015年 apple. All rights reserved.
//

#import "KouDaiCellPushViewController.h"
#import "AFNetworking.h"
#import "KouDaiDetailModel.h"
#import "attraction_trip_tagsArrMOdel.h"
#import "LZXHelper.h"
#import "NSString+Hashing.h"
#import "UIImageView+AFNetworking.h"
#import "ScrollViewTableViewCell.h"
#import "attraction_contentsModel.h"
#import "YouJiViewController.h"
#import "FMDBDataBaseManager.h"
#define URL (@"http://chanyouji.com/api/attractions/%@.json")
//定义一个宏，声明弱引用
#define WeakSelf __weak typeof(self) weakSelf = self
@interface KouDaiCellPushViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    NSMutableArray *_dataArr;
    UILabel *_lable;
    UIActivityIndicatorView *_activity;
}
@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, strong) UILabel *lable;
@property (nonatomic, strong) UIActivityIndicatorView *activity;
@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)KouDaiDetailModel * model;
@property (nonatomic,assign)BOOL iscollection;
@end

@implementation KouDaiCellPushViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self checkDidCache];
    
    self.title = self.headName;
    _dataArr = [[NSMutableArray alloc]initWithCapacity:0];
    [self getData];
    
    [self createNavigationRightButton];
    [self createView];

}

//检查是否被收藏
- (void)checkDidCache {
    FMDBDataBaseManager *manager = [FMDBDataBaseManager shareMagager];
    if ([manager findData:self.ID].count != 0) {
        self.iscollection = YES;
    } else {
        self.iscollection = NO;
    }
}

- (void)createNavigationRightButton{
    UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 30, 30)];
    [button setImage:[UIImage imageNamed:@"uncollection-Small.png"] forState:UIControlStateNormal];
    [button setImage:[UIImage imageNamed:@"collection-Small.png"] forState:UIControlStateSelected];
    if (_iscollection) {
        button.selected = YES;
    }else{
        button.selected = NO;
    }
    //[button setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 5, 0)];
    [button addTarget:self action:@selector(rightAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:button];
    self.navigationItem.rightBarButtonItem = rightItem;
}
- (void)rightAction:(UIButton *)button{
    if (!button.selected) {
        FMDBDataBaseManager *manager = [FMDBDataBaseManager shareMagager];
        [manager insertDataWithModel:self.model];
        button.selected = YES;
    }else{
        FMDBDataBaseManager *manager = [FMDBDataBaseManager shareMagager];
        [manager deleteDataWithModel:self.model];
        button.selected = NO;
    }
    _iscollection = !_iscollection;
}

-(void)getData
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
   
    //NSLog(@"网址 ：%@",[NSString stringWithFormat:URL,self.ID]);
    WeakSelf;
    [manager GET:[NSString stringWithFormat:URL,self.ID] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        
        NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
       // NSLog(@"%@",dic);
        
        weakSelf.model = [[KouDaiDetailModel alloc]initWithDictionary:dic error:nil];
        //NSLog(@"%@",_model);
        weakSelf.dataArr = (NSMutableArray *)_model.attraction_trip_tags;
        //NSLog(@"=====%@",_dataArr);
        [weakSelf.tableView reloadData];
        
        //下载完成之后 把数据 保存本地沙盒中(缓存)
        //直接把下载的二进制数据  responseObject写入本地文件
        NSString *path = [LZXHelper getFullPathWithFile:[NSString stringWithFormat:URL,self.ID]];
        //写文件
        NSData *data = (NSData *)responseObject;
        //每一页 都做 缓存
        [data writeToFile:path atomically:YES];
        [weakSelf.lable removeFromSuperview];
        [weakSelf.activity removeFromSuperview];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
    }];
}


-(void)createView
{
    _tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:0];
    [self.view addSubview:_tableView];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    //注册
    [_tableView registerNib:[UINib nibWithNibName:@"FirstCell" bundle:nil] forCellReuseIdentifier:@"678"];
    //注册
    //[_tableView registerNib:[UINib nibWithNibName:@"ScrollViewTableView" bundle:nil] forCellReuseIdentifier:@"789"];
    
    _lable = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 60, 60)];
    _lable.center = self.view.center;
    [self.view addSubview:_lable];
    _lable.backgroundColor = [UIColor colorWithHue:50/255.f saturation:50/255.f brightness:50/255.f alpha:0.6];
    
    //活动指示器
    _activity = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    
    [self.view addSubview:_activity];
    _activity.center = self.view.center;
    [_activity startAnimating];

    
    [self createNavigationBar:9];
    [self.buttonA setImage:[UIImage imageNamed:@"collection-Small"] forState:UIControlStateNormal];
    self.back.text = @"口袋书";
    
}

#pragma mark －代理方法 －
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    //NSLog(@"%ld",_dataArr.count + 3);
    return _dataArr.count + 1;
}

//每组有多少行
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //没加载到数据之前，返回0组
    if (_dataArr.count == 0) {
        return 0;
    }else{
        //如果不是第一组或者不是最后一组
    if (0 < section && section <= _model.attraction_trip_tags.count) {
        
        attraction_trip_tagsArrMOdel * model = [_dataArr objectAtIndex:section - 1];
        
        return model.attraction_contents.count;
    }
    return 1;
    }
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //第一组
    if (indexPath.section == 0) {
       UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"678"];
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        UIImageView * backImgV = (UIImageView *)[cell.contentView viewWithTag:1000];
        [backImgV setImageWithURL:[NSURL URLWithString:_model.image_url]];
        
        UILabel * lable1 = (UILabel *)[cell.contentView viewWithTag:1001];
        lable1.text = _model.name_zh_cn;
        UILabel * lable2 = (UILabel *)[cell.contentView viewWithTag:1002];
        lable2.text = _model.name_en;
        
//        UILabel * lable3 = (UILabel *)[cell.contentView viewWithTag:1003];
//        lable3.text = [NSString stringWithFormat:@"%ld",_model.photos_count];
//        UILabel * lable4 = (UILabel *)[cell.contentView viewWithTag:1004];
//        lable4.text = [NSString stringWithFormat:@"%ld",_model.attraction_trips_count];
        
        UILabel * lable5 = (UILabel *)[cell.contentView viewWithTag:1005];
        lable5.text = _model.desc;
        

        return cell;
    }else {
      ScrollViewTableViewCell *  cell = [tableView dequeueReusableCellWithIdentifier:@"789"];
        
        if (!cell) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"ScrollViewTableViewCell" owner:self options:nil]lastObject];
       }
        cell.delegate = self;
        attraction_trip_tagsArrMOdel * model = [_model.attraction_trip_tags objectAtIndex:indexPath.section - 1];
        
        NSArray * arr = model.attraction_contents;
        attraction_contentsModel * subModel = [arr objectAtIndex:indexPath.row];
        NSArray * imageArr = subModel.notes;
        
        [cell createScrollViewWithArr:imageArr];
        // NSLog(@"%@",cell.imageScrollView);
        cell.descLable.text = subModel.desc;
        
       return cell;
    }
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        CGFloat height = [LZXHelper textHeightFromTextString:_model.desc width:[UIScreen mainScreen].bounds.size.width - 20 fontSize:15.f];
        return height + 230;
    }else if(0 < indexPath.section && indexPath.section <= _model.attraction_trip_tags.count){
        attraction_trip_tagsArrMOdel * model = [_model.attraction_trip_tags objectAtIndex:indexPath.section - 1];
        NSArray * arr = model.attraction_contents;
        attraction_contentsModel * subModel = [arr objectAtIndex:indexPath.row];
        float height = [LZXHelper textHeightFromTextString:subModel.desc width:[UIScreen mainScreen].bounds.size.width - 20 fontSize:15.f];
        return height + 110;
        
    }
    return 200;
}



//每个透视图的高度
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 0.001;
    }
    
    return 30;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.001;
}


//头视图的内容
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UILabel * lable = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 30)];
    
    lable.textAlignment = 1;
    lable.backgroundColor = [UIColor colorWithHue:240/255.f saturation:230/255.f brightness:240/255.f alpha:0.8];
    
    if (section > 0 && section <=_model.attraction_trip_tags.count) {
        
        attraction_trip_tagsArrMOdel * model = [_model.attraction_trip_tags objectAtIndex:section - 1];
       // NSLog(@"%@",dic);
        lable.text = model.name;
        
        return lable;

    }
    //lable.text = @"附近景点";
    return lable;
}

//代理方法
-(void)HidenNavigationBar
{
    self.navigationController.navigationBar.hidden = YES;
}
-(void)showNavigationBar
{
    self.navigationController.navigationBar.hidden = NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
